package com.crb.crm.manage.web.biz.excel;

import com.crb.crm.manage.excel.ExcelTemplate;
import com.crb.crm.manage.pojo.User;
import com.crb.crm.manage.service.biz.UploadRecordService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author huangjian
 */
@Controller
@RequestMapping("/excel")
public class ExcelController {
	
	private static final Logger logger = LoggerFactory
			.getLogger(ExcelController.class);

	@Autowired
	private UploadRecordService uploadRecordService;

	/**
	 * excel上传模板下载
	 */
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	@ResponseBody
	public void download(HttpServletResponse response,String templateCode) throws UnsupportedEncodingException {
		ExcelTemplate byTemplateCode = ExcelTemplate.findByTemplateCode(templateCode);
		String filepath = byTemplateCode.getFileName();
		// 配置文件下载
		response.setHeader("content-type", "application/octet-stream");
		response.setContentType("application/octet-stream");
		// 下载文件能正常显示中文
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filepath, "UTF-8"));
		// 实现文件下载
		byte[] buffer = new byte[1024];
		InputStream fis = null;
		BufferedInputStream bis = null;
		try {
			Resource resource = new ClassPathResource("/excel/"+filepath);
			fis = resource.getInputStream();
			bis = new BufferedInputStream(fis);
			OutputStream os = response.getOutputStream();
			int i = bis.read(buffer);
			while (i != -1) {
				os.write(buffer, 0, i);
				i = bis.read(buffer);
			}
			System.out.println("Download  successfully!");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Download  failed!");
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 批量上传
	 * @return map
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> upload(@RequestParam("file") MultipartFile file,
									  @RequestParam("templateCode")String templateCode) {
		logger.debug("批量上传数据，templateCode="+templateCode);
		Map<String, Object> map = new HashMap<>();
		if (null == file) {
			logger.debug("批量上传数据==请求参数有误，请您稍后再试");
			map.put("msg", "请求参数有误，请您稍后再试");
			return map;
		}
		User existUser = (User) SecurityUtils.getSubject().getPrincipal();
		if (null == existUser) {
			map.put("msg", "您未登录或登录超时，请您登录后再试");
			return map;
		}
		return uploadRecordService.upload(file,templateCode,existUser);
	}
}
